import logging, logging.handlers
import os

LOGS_DIR = os.path.expanduser('~/.sms-middleware/logs')
try:
    os.makedirs(LOGS_DIR)
except:
    pass

debug_levels_dict = {
    'CRITICAL':logging.CRITICAL,
    'critical':logging.CRITICAL,
    'c':logging.CRITICAL,
    'ERROR':logging.ERROR,
    'error':logging.ERROR,
    'e':logging.ERROR,
    'WARNING':logging.WARNING,
    'warning':logging.WARNING,
    'w':logging.WARNING,
    'INFO':logging.INFO,
    'info':logging.INFO,
    'i':logging.INFO,
    'DEBUG':logging.DEBUG,
    'debug':logging.DEBUG,
    'd':logging.DEBUG,
}

class loggers(logging.Logger):
    """writing logs in directory PWD/logs/
    also take care of log rotating and formatting """

    def __init__(self, name, filename, debug_level=None, screen=None):
        """name is the name visible in log file
        if pure is set no additional informations (like timestamp) is added to log file
        returns loggers instance"""

        logging.Logger.__init__(self, name)
        
        if not debug_level:
            log_handler = logging.FileHandler('/dev/null')
            log_handler.setLevel(logging.CRITICAL)
            self.addHandler(log_handler)
            return
        
        log_file = os.path.join(LOGS_DIR, filename)
        #rotating every one day, at most 10 log files in directory (rotating)
        log_handler = logging.handlers.TimedRotatingFileHandler(log_file, 'D', 1, 5)
        
        log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s',
                                          '%y/%m/%d %H:%M:%S')
        log_handler.setFormatter(log_formatter)
        log_handler.setLevel(debug_levels_dict[debug_level])
        self.addHandler(log_handler)
        
        self.setLevel(debug_levels_dict[debug_level])
        
        if screen and debug_level:
            console = logging.StreamHandler()
            console.setLevel(debug_levels_dict[debug_level])
            formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s',
                                          '%y/%m/%d %H:%M:%S')
            console.setFormatter(formatter)
            
            # add the handler to the root logger
            self.addHandler(console)

